﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class Popup_SelectFriend : Popup_Base
{
	const string SELECT_FRIEND_CELL_NAME = "Cell - Select Friend";
	
	public GameObject emptyListObject;
	public GameObject selectFriendCell;
	public UIGrid selectFriendGrid;
	public GameObject sceneObject;
	
	string initialFriendNameText;
	
	Dictionary<int, FriendModel> selectFriendList = new Dictionary<int, FriendModel>();
	Dictionary<int, GameObject> selectFriendObjectList = new Dictionary<int, GameObject>();
	
	public override void BackButton()
	{
		PopupManager.PopPopup();
	}
	
	public void SelectFriendProcess(int selectedIndexPath)
	{
		if (sceneObject.GetComponent<MessageScene>() != null)
		{
			sceneObject.GetComponent<MessageScene>().receiverId = selectFriendList[selectedIndexPath].id;
			sceneObject.GetComponent<MessageScene>().receiverNameLabel.text = selectFriendList[selectedIndexPath].name;
		}
		
		else if (sceneObject.GetComponent<Popup_WriteMessage>() != null)
		{
			sceneObject.GetComponent<Popup_WriteMessage>().receiverId = selectFriendList[selectedIndexPath].id;
			sceneObject.GetComponent<Popup_WriteMessage>().receiverNameInput.value = selectFriendList[selectedIndexPath].name;
		}

//		sceneObject.GetComponent<MessageScene>().receiverId = selectFriendList[selectedIndexPath].id;
//		sceneObject.GetComponent<MessageScene>().receiverNameInput.value = selectFriendList[selectedIndexPath].name;
		BackButton();
	}

	public override void StartInit ()
	{
		NetworkManager.Instance.C2S_FRIEND_LIST(new int[1]{1}, ( responseData ) => {
			
			if (responseData.ecode != 0)
			{
				NGUITools.SetActive(emptyListObject, true);
				return;
			}
			
			GameObject g = null;
			int idx = 0;
			
			if (responseData.data.Count <= 0)
			{
				NGUITools.SetActive(emptyListObject, true);
				return;
			}
			
			NGUITools.SetActive(emptyListObject, false);
			
			foreach (FriendModel fm in responseData.data)
			{
				g = NGUITools.AddChild(selectFriendGrid.transform.gameObject, selectFriendCell);
				g.transform.localScale = Vector3.one;
				g.name = SELECT_FRIEND_CELL_NAME;
				
				SelectFriendCell sfc = g.GetComponent<SelectFriendCell>();
				sfc.indexPath = idx;
				
				sfc.nameLabel.text = fm.name;
				sfc.levelLabel.text = string.Format("Lv {0}", fm.lv.ToString());
				
				selectFriendObjectList.Add (idx, g);
				selectFriendList.Add (idx, fm);
				
				NGUITools.SetActive(g, true);
				
				idx++;
			}
			selectFriendGrid.Reposition();
		});
	}
}
